package com.qingke.easyjava.jdbc.command.impl;

import com.qingke.easyjava.jdbc.app.BeSuperDao;
import com.qingke.easyjava.jdbc.command.PlayerCommand;
import com.qingke.easyjava.jdbc.pojo.Answer;
import com.qingke.easyjava.jdbc.pojo.Player;
import com.qingke.easyjava.jdbc.pojo.Question;
import com.qingke.easyjava.jdbc.util.QingkeConsole;

public class AcceptCommand extends PlayerCommand{

	public AcceptCommand(Player playerProfile) {
		super(playerProfile);
	}

	@Override
	public void execute() {
		
		BeSuperDao dao = new BeSuperDao();
		long qid = QingkeConsole.askUserInputInt("Please enter question id:");
		
		Question question = dao.getQuestion(qid);
		if(question == null) {
			QingkeConsole.println("Invalid Question id!");
			return;
		}
		
		if(question.getFrom().getId() != playerProfile.getId()) {
			QingkeConsole.println("The question is not belong to you!");
			return;
		}
		if(question.isOpen()) {
			QingkeConsole.println("The question has been solved!");
		}
		
		long aid = QingkeConsole.askUserInputInt("Please enter answer id:");
		Answer answer = dao.getAnswer(aid);
		
		if(answer == null) {
			QingkeConsole.println("Invalid Answer id!");
			return;
		}
		
		//accept
		question.setOpen(false);
		question.setBestanswer(answer);
		
		answer.setBestAnswer(true);
		
		int credit = question.getCredit();
		
		Player questionFrom = question.getFrom();
		int fromScore = question.getFrom().getScore();
		fromScore -= credit;
		questionFrom.setScore(fromScore);
		
		credit = (credit <= 0) ? 10 : credit;
		Player answerFrom = answer.getFrom();
		int toScore = answer.getFrom().getScore();
		toScore += credit;
		answerFrom.setScore(toScore);
		
		dao.acceptAnswer1(answer);
		dao.acceptAnswer2(answer);
	}

}
